<template>
  <!-- 在售商品统计 折线图 -->
  <div class="card_box">
    <div class="header">
      <div class="title flex">
        <subtit title="营销数据趋势图"></subtit>

        <span class="date-range">{{ formatDateRange  }}</span>
        <!-- <div class="shu-refresh" @click="getQushi">
          <span class="font14">刷新</span>
          <span class="el-icon-refresh-right"></span>
        </div> -->
      </div>

    </div>
    <div id="soldCharts"></div>
  </div>
</template>

<script>
import subtit from "@/components/indexComponents/subtit.vue";
import { qushi } from "@/api/dmgt/index";
import * as echarts from "echarts";
import EleResize from '@/utils/esresize';

export default {
  props: {
    queryParams: {
      type: Object,
      default: () => ({})
    },
     formatDateRange:{
       type: [Array, String],
      default: () => []
    }
  },
  components: { subtit },
  name: "",
    
  data() {
    return {
      myChart1: null,
      xData: [
       
      ], // 日期
      quantityList: [], // 数量
      amountList: [],   // 金额

    };
  },
  created() {

  },
  // watch: {
  //   queryParams: {
  //     handler(newParams) {
  //       // 当查询参数变化时，重新获取数据
  //       if (newParams && Object.keys(newParams).length > 0) {
  //         this.getQushi();
  //       }
  //     },
  //     deep: true,
  //     immediate: false
  //   }
  // },
  beforeDestroy() {
    // 销毁图表实例
    if (this.myChart1) {
      this.myChart1.dispose();
      this.myChart1 = null;
    }
  },
  mounted() {
    this.$nextTick(() => {
      var chartDom = document.getElementById("soldCharts");
      this.myChart1 = echarts.init(chartDom, null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      var resizeDiv = document.getElementById('soldCharts')
      EleResize.on(resizeDiv, () => {
        this.myChart1.resize()
      })
       this.getQushi();
    });
  },
  methods: {
    getQushi() {
       if (this.myChart1) this.myChart1.showLoading({text: '加载中...', color: '#6c5dd3'});
      // 清空之前的数据
      this.xData = [];
      this.quantityList = [];
      this.amountList = [];
      
      qushi(this.queryParams).then(res => {
        if (res.code === 200) {
           const sortedHours = Object.keys(res.data).sort((a, b) => parseInt(a) - parseInt(b));
          let formattedHour
          sortedHours.forEach(hour => {
            if(sortedHours.length == 24) {
                // 将小时数字转换为 HH:00 格式
             formattedHour = String(hour).padStart(2, '0') + ':00';
            }else {
              formattedHour = hour
            }
          
            this.xData.push(formattedHour);
            this.quantityList.push(res.data[hour].backCot); // 回收订单数数组
            this.amountList.push(res.data[hour].saleCot); // 销售订单数数组
          });

        }
        this.initCharts1()
         if (this.myChart1) this.myChart1.hideLoading();
      }).catch(()=> {
        if (this.myChart1) this.myChart1.hideLoading();

      });
    },
  
    initCharts1() {
      const colors = [
        "rgb(97, 105, 224)",   // 数量-绿色
        "rgb(241, 210, 25)"   // 金额-蓝色
      ];
      
      // 根据数据量决定是否显示 dataZoom
      const showDataZoom = this.xData.length > 15; // 当数据点超过15个时显示滚动条
      
      let option = {
        tooltip: {
          trigger: "axis",
          backgroundColor: "#fff",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: { color: "#333" },
          axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: 'rgba(145, 145, 145, 0.3)',
          },
        },
          formatter: (params) => {
            let str = params[0].axisValue + "<br/>";
            params.forEach(item => {
              str += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background:${item.color}"></span>`;
              str += `${item.seriesName}: <b>${item.value}</b><br/>`;
            });
            return str;
          }
        },
        color: colors,
        legend: {
          itemHeight: 10,
          itemWidth: 10,
          itemGap: 30,
          data: [
            { name: "回收订单数", textStyle: { color: '#666' }, icon: 'circle', },
            { name: "销售订单数", textStyle: { color: '#666' }, icon: 'circle' },

          ],

          top: 0,
          left: "center"
        },
        
        grid: { 
          left: 50, 
          right: 50, 
          top: 40, 
          bottom: showDataZoom ? 80 : 46 // 如果有滚动条，底部留更多空间
        },
        dataZoom: showDataZoom ? [
          {
            type: 'slider',
            start:0,//默认为0
            startValue:0,
            endValue:40,
            end: Math.min(100, (20 / this.xData.length) * 100), // 固定显示15个数据点
            xAxisIndex: [0],
            handleSize: 0,//滑动条的 左右2个滑动条的大小
            height: 10,//组件高度
            bottom: 0,//右边的距离
            borderColor: "#e3e3e3",
            fillerColor: 'rgb(97, 105, 224)',
            borderRadius:16,
            zoomLock: true, 
             brushSelect: false, // 是否开启刷选功能，可以理解为拖拽区域的宽度
            backgroundColor: '#e3e3e3',//两边未选中的滑动条区域的颜色
            showDataShadow: false,//是否显示数据阴影 默认auto
            showDetail: false,//即拖拽时候是否显示详细数值信息 默认true
          
            filterMode: 'filter',
            zlevel:-10,

          },
          {
            type: 'inside',
            xAxisIndex: [0],
            zoomOnMouseWheel:false, //滚轮不触发缩放
            moveOnMouseMove:true,   //鼠标移动触发平移
            moveOnMouseWheel:true,  //鼠标滚轮触发平移

          }
        ] : [],
        xAxis: {
          type: "category",
          data: this.xData,
          boundaryGap: false,
          axisLine: { lineStyle: { color: "#e2e8ff" } },
          axisLabel: { 
            color: "#8D9AA9", 
            show: true,
            rotate: showDataZoom ? 45 : 0, // 数据多时旋转标签避免重叠
            interval: showDataZoom ? 'auto' : 0 // 数据多时自动间隔显示
          },
          // splitLine: { show: true, lineStyle: { color: "#EAEBF0", type: "dotted" } },

        },
        yAxis: [
          {
            name: '单位/单',
            type: "value",
            axisLine: { lineStyle: { color: "#e2e8ff" } }, // 轴线颜色
            axisLabel: { color: '#8D9AA9' },
            splitLine: { lineStyle: { color: "#EAEBF0", type: "dotted" } },
            nameTextStyle: { color: '#C8D2DD' }, // y轴名称颜色
           max: function(value) {
               return Math.floor(value.max * 1.1);
            }
          },

        ],
        series: [
          {
            name: "回收订单数",
            type: "line",
            yAxisIndex: 0,
           smooth:true, 
            data: this.quantityList,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(247, 248, 254)" },
                { offset: 1, color: "rgba(247, 248, 254,0.2)" }

              ])
            }
          },
          {

            name: "销售订单数",
            type: "line",
            smooth:true, 
            data: this.amountList,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(250, 246, 231)'
                },
                {
                  offset: 1,
                  color: 'rgba(250, 246, 231,0.2)'
                }
              ])
            }
          }
        ]
      };
      this.myChart1 && this.myChart1.setOption(option);
    },
  },
};
</script>

<style scoped lang="scss">
.card_box {
  padding: 0 24px 12px 24px;
  position: relative;

  .flex {}

  .time_box {}
}

#soldCharts {
  width: 100%;
  height: 450px;
}

.timers {
  font-size: 14px;
  margin-right: 6px;
}

.card_flex {
  justify-content: space-between;
  align-items: center;
}

.time_text {
  color: #999;
  margin-left: 6px;
}


.header {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: 600;
    color: #222;

    .date-range {
      font-size: 12px;
      color: #666;
      margin-left: 8px;
    }
  }

  .collapse-btn {
    font-size: 13px;
    color: #666;

    i {
      font-size: 12px;
    }
  }
}

.header {
  .flex {
    align-items: center;
  }

  .num-title {
    font-size: 18px;
    color: #333333;
    font-weight: bold;
  }

 
}
</style>
